package com.tianluo.tianluobookstore.controller.user;

import com.tianluo.tianluobookstore.OrderPO;
import com.tianluo.tianluobookstore.domain.view.OrderVO;
import com.tianluo.tianluobookstore.request.CreateOrderRequest;
import com.tianluo.tianluobookstore.response.BaseResponse;
import com.tianluo.tianluobookstore.service.OrderService;
import com.tianluo.tianluobookstore.service.RedisLockTemplate;
import com.tianluo.tianluobookstore.task.OrderCancelTask;
import com.tianluo.tianluobookstore.task.OrderDelayItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@RestController
@Slf4j
public class OrderController {

    @Autowired
    private RedisLockTemplate redisLockTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderCancelTask orderCancelTask; // 注入你的取消任务类

    @PostMapping("/createOrder")
    public BaseResponse<String> createOrder(@RequestBody CreateOrderRequest request, @RequestAttribute("phoneNumber") String phoneNumber) {

        OrderPO orderPO = orderService.queryOrderByBizSeq(request.getBizSeq());
        if (Objects.nonNull(orderPO)) {
            return BaseResponse.success("下单成功");
        }

        request.setUserId(Long.parseLong(phoneNumber));
        String result = redisLockTemplate.executeWithLock(String.valueOf(request.getBookId()), 10, () -> orderService.createOrder(request));

        if (StringUtils.isNotBlank(result)) {
            long delayTime = 30 * 60 * 1000; // 30分钟（单位为毫秒）
            OrderDelayItem orderDelayItem = new OrderDelayItem(request.getBizSeq(), delayTime);
            orderCancelTask.addOrder(result,delayTime); // 将取消任务放入 DelayQueue
        }

        return BaseResponse.success(result);
    }

    @GetMapping("/getOrderDetails")  // 去掉路径中的 {orderId}
    public BaseResponse<OrderVO> getOrderDetails(@RequestParam String orderId) {

        OrderPO orderPO = orderService.queryOrderByOrderId(orderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orderPO, orderVO);

        LocalDateTime localDateTime = orderPO.getCreatedTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        // 创建格式化对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedDate = localDateTime.format(formatter);
        orderVO.setCreatedTime(formattedDate);

        return BaseResponse.success(orderVO); // 返回 200 OK 和订单 DTO
    }

}
